package com.tianzmp.ttq.admin.security;

import com.tianzmp.ttq.admin.common.BaseResult;
import com.tianzmp.ttq.admin.common.Result;
import com.tianzmp.ttq.admin.exception.AdminBusinessException;
import com.tianzmp.ttq.admin.exception.ErrorEnum;
import lombok.extern.log4j.Log4j2;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;


/**
 * 统一异常处理
 *
 * @author zhumengping
 */
@ControllerAdvice
@Log4j2
public class GlobalExceptionHandler {

    /**
     *  拦截MultipartException类的异常
     * @param e
     * @return
     */
    @ExceptionHandler(AdminBusinessException.class)
    @ResponseBody
    public BaseResult exceptionHandler(AdminBusinessException e){
        return Result.error(e.getCode(),e.getMessage());
    }

    /**
     * 全局注解异常
     *
     * @param exception 异常
     * @return 结果集
     */
    @ExceptionHandler(value = BindException.class)
    @ResponseBody
    public BaseResult handlerException(BindException exception) {
        log.info("exception:{}", exception);
        return Result.error(getMsg(exception.getBindingResult().getAllErrors()));

    }


    /**
     * 全局注解异常
     *
     * @param exception 异常
     * @return 结果集
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public BaseResult handlerException(MethodArgumentNotValidException exception) {
        return Result.error(ErrorEnum.USER20000008.getCode(),
                getMsg(exception.getBindingResult().getAllErrors()));

    }


    private String getMsg(List<ObjectError> objectErrors) {
        StringBuffer stringBuffer = new StringBuffer();
        int index = 0;
        for (ObjectError objectError : objectErrors) {
            stringBuffer.append(objectError.getDefaultMessage());
            index++;
            if (index != objectErrors.size()) {
                stringBuffer.append(";");
            }
        }
        log.info(stringBuffer.toString());
        return stringBuffer.toString();
    }


}
